package com.zscat.mallplus.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dianping.dzopen.apis.TuangouAPI;
import com.dianping.dzopen.valuebuilder.RequestIdBuilder;
import com.dianping.dzopen.valuebuilder.TimestampValueBuilder;
import com.douyin.open.api.TuangouHexiaoApi;
import com.douyin.open.api.TuangouHexiaoPrepareApi;
import com.douyin.open.models.TuangouHexiaoPrepareResponse200;
import com.douyin.open.models.TuangouHexiaoPrepareResponse200Data;
import com.douyin.open.models.TuangouHexiaoResponse200;
import com.douyin.open.models.TuangouHexiaoResponse200Data;
import com.jpay.ext.kit.PaymentKit;
import com.jpay.ext.kit.StrKit;
import com.jpay.util.StringUtils;
import com.jpay.weixin.api.WxPayApi;
import com.zscat.mallplus.dms.entity.DmsOrder;
import com.zscat.mallplus.dms.service.*;
import com.zscat.mallplus.dms.vo.DriverOrderParam;
import com.zscat.mallplus.enums.OrderStatus;
import com.zscat.mallplus.enums.TaskType;
import com.zscat.mallplus.qsg.*;
import com.zscat.mallplus.single.ApiBaseAction;
import com.zscat.mallplus.sys.mapper.SysAppletSetMapper;
import com.zscat.mallplus.ums.entity.SysAppletSet;
import com.zscat.mallplus.ums.entity.UmsMember;
import com.zscat.mallplus.ums.service.IUmsMemberService;
import com.zscat.mallplus.ums.service.RedisService;
import com.zscat.mallplus.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 订单管理Controller
 * https://github.com/shenzhuan/mallplus on 2018/8/30.
 */
@Slf4j
@Controller
@Api(tags = "OmsPortalOrderController", description = "订单管理")
@RequestMapping("/api/order")
public class OmsPortalOrderController extends ApiBaseAction {
    @Autowired
    private IUmsMemberService umsMemberService;
    @Autowired
    private IDmsOrderService dmsOrderService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private IDeviceTaskService taskService;
    @Autowired
    private CertificateService certificateService;
    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private IQsgMemberStoreService memberStoreService;
    @Autowired
    private WxMsgService wxMsgService;
    @Autowired
    private IQsgRechargeOrderService rechargeOrderService;
    @Autowired
    private IMealService mealService;

    @Autowired
    private IntegralService integralService;

    @Resource
    private SysAppletSetMapper appletSetMapper;

    @Autowired
    private IQsgStoreService qsgStoreService;
    @Autowired
    private IQsgHexiaoService hexiaoService;
    @Autowired
    private IQsgIntegralDetailService detailService;
    @Autowired
    private MemberUtil memberUtil;


    @ApiOperation("根据id查询驾校订单")
    @RequestMapping(value = "/getDmsOrderDetail", method = RequestMethod.GET)
    @ResponseBody
    public Object getDmsOrderDetail(@RequestParam(value = "id", required = false, defaultValue = "0") Long id) {
        DmsOrder orderDetailResult = dmsOrderService.getById(id);
        return new CommonResult().success(orderDetailResult);
    }

    @ApiOperation("根据id查询驾校订单")
    @RequestMapping(value = "/getOrderDetail", method = RequestMethod.POST)
    @ResponseBody
    public Object getOrderDetail(@RequestBody DmsOrder order) {
        DmsOrder orderDetailResult = dmsOrderService.getById(order.getId());
        QsgDevice device = deviceService.getById(orderDetailResult.getDeviceId());
        QsgMeal meal = mealService.getById(orderDetailResult.getMealId());
        UmsMember member = umsMemberService.getById(orderDetailResult.getMemberId());
        orderDetailResult.setDevice(device);
        orderDetailResult.setMeal(meal);
        orderDetailResult.setMember(member);
        return new CommonResult().success(orderDetailResult);
    }

    @ApiOperation("取消订单")
    @RequestMapping(value = "/cannelOrder")
    @ResponseBody
    public Object cannelOrder(Long orderId) {
        DmsOrder order = dmsOrderService.getById(orderId);
        if (order.getOrderStatus() == OrderStatus.HAS_PAYMONEY.getValue()) {
            order.setOrderStatus(OrderStatus.WAIT_CANNEL.getValue());
            dmsOrderService.updateById(order);
            wxMsgService.sendCannelMsg(order);
        }
        return new CommonResult().success(order);
    }

    @ApiOperation("确认取消订单")
    @RequestMapping(value = "/agreeCannelOrder", method = RequestMethod.POST)
    @ResponseBody
    public Object agreeCannelOrder(@RequestBody DmsOrder entity) {
        SysAppletSet sysAppletSet = appletSetMapper.selectOne(new QueryWrapper<>());
        DmsOrder order = dmsOrderService.getById(entity.getId());
        QsgStore store = qsgStoreService.getById(order.getStoreId());
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("order_sn",order.getOrderSn());
        Certificate certificate = certificateService.getOne(queryWrapper);
        if (null!=certificate){
            certificate.setCertificateStatus(0);
            certificate.setOrderSn("");
            certificateService.updateById(certificate);
            order.setOrderStatus(OrderStatus.REFUND.getValue());
            dmsOrderService.updateById(order);
            return new CommonResult().success(order);
        }
        order.setOrderStatus(OrderStatus.REFUND.getValue());
        if (0 != order.getIntegral()) {
            //积分订单直接返回积分
            QueryWrapper qw = new QueryWrapper();
            qw.eq("store_id", order.getStoreId());
            qw.eq("member_id", order.getMemberId());
            QsgIntegral integral = integralService.getOne(qw);
            integral.setIntegral(integral.getIntegral() + order.getIntegral());
            integralService.updateById(integral);
            dmsOrderService.updateById(order);
        }else {
            //微信退款
            if (order.getIsSharing()==1){
                try {
                    //需要分账还未分账的订单退款，需要解冻该笔订单的金额
                    Map<String, String> finishParams = new TreeMap<>();
                    finishParams.put("mch_id", store.getServerMchId());//服务商
                    finishParams.put("appid", sysAppletSet.getAppid());//服务商appid
                    finishParams.put("sub_mch_id", store.getMchId());//出资方 根据订单的storeId获取
                    finishParams.put("transaction_id", order.getWxOrderSn());//微信订单号 根据订单获取
                    finishParams.put("nonce_str", System.currentTimeMillis() + "");
                    finishParams.put("out_order_no",order.getOrderSn());
                    finishParams.put("description","用户退款");
                    String sign = WechatUtil.arrayHmacsha(finishParams,store.getServerKey());
                    finishParams.put("sign",sign);
                    //上线后需改为线上模式
                    String i = WxPayApi.profitsharingfinish(finishParams, store.getServerCertPath(), store.getServerMchId());//参数 证书地址 服务商证书密码默认即商户号
                    Map<String, Object> resultUn = XmlUtil.xmlStrToMap(i);
                    String return_code = MapUtils.getString("return_code", resultUn);
                    String result_code = MapUtils.getString("result_code", resultUn);
                    if (result_code.equalsIgnoreCase("SUCCESS")&&return_code.equalsIgnoreCase("SUCCESS")){
                        //解冻完成以后退款
                        Map<String, String> params = new HashMap<String, String>();
                        params.put("appid", sysAppletSet.getAppid());//服务商appid
                        params.put("mch_id", store.getServerMchId());//服务商appid
                        params.put("sub_mch_id",store.getMchId());//退款的商户号
                        params.put("nonce_str", System.currentTimeMillis() + "");
                        params.put("transaction_id",order.getWxOrderSn());
                        params.put("out_refund_no", System.currentTimeMillis() + "");
                        params.put("total_fee", order.getPrice().multiply(new BigDecimal(100)).intValue()+"");
                        params.put("refund_fee", order.getPrice().multiply(new BigDecimal(100)).intValue()+"");
                        params.put("sign_type","HMAC-SHA256");
                        params.put("sign",WechatUtil.arrayHmacsha(params,store.getServerKey()));
                        i = WxPayApi.orderRefund(false, params, store.getServerCertPath(), store.getServerMchId());
                        resultUn = XmlUtil.xmlStrToMap(i);
                        return_code = MapUtils.getString("return_code", resultUn);
                        result_code = MapUtils.getString("result_code", resultUn);
                        if (result_code.equalsIgnoreCase("SUCCESS")&&return_code.equalsIgnoreCase("SUCCESS")){
                            dmsOrderService.updateById(order);
                            QueryWrapper qw = new QueryWrapper();
                            qw.eq("order_sn", order.getOrderSn());
                            List<QsgDeviceTask> tasks = taskService.list(qw);
                            if (null != tasks && tasks.size() > 0) {
                                for (QsgDeviceTask task : tasks) {
                                    task.setStatus(1);
                                    task.setUpdateReason("订单退款时更新");
                                    task.setUpdateTime(new Date());
                                    taskService.updateById(task);
                                }
                            }
                        }
                        log.info(i);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            } else {
                try {
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("appid", sysAppletSet.getAppid());//服务商appid
                    params.put("mch_id", store.getServerMchId());//服务商appid
                    params.put("sub_mch_id", store.getMchId());//退款的商户号
                    params.put("nonce_str", System.currentTimeMillis() + "");
                    params.put("transaction_id", order.getWxOrderSn());
                    params.put("out_refund_no", System.currentTimeMillis() + "");
                    params.put("total_fee", order.getPrice().multiply(new BigDecimal(100)).intValue() + "");
                    params.put("refund_fee", order.getPrice().multiply(new BigDecimal(100)).intValue() + "");
                    params.put("sign_type", "HMAC-SHA256");
                    params.put("sign", WechatUtil.arrayHmacsha(params, store.getServerKey()));
                    String i = WxPayApi.orderRefund(false, params, store.getServerCertPath(), store.getServerMchId());
                    Map<String, Object> resultUn = XmlUtil.xmlStrToMap(i);
                    String return_code = MapUtils.getString("return_code", resultUn);
                    String result_code = MapUtils.getString("result_code", resultUn);
                    if (result_code.equalsIgnoreCase("SUCCESS") && return_code.equalsIgnoreCase("SUCCESS")) {
                        dmsOrderService.updateById(order);
                        QueryWrapper qw = new QueryWrapper();
                        qw.eq("order_sn", order.getOrderSn());
                        List<QsgDeviceTask> tasks = taskService.list(qw);
                        if (null != tasks && tasks.size() > 0) {
                            for (QsgDeviceTask task : tasks) {
                                task.setStatus(1);
                                task.setUpdateReason("订单退款时更新");
                                task.setUpdateTime(new Date());
                                taskService.updateById(task);
                            }
                        }
                    }
                    log.info(i);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        return new CommonResult().success(order);
    }

    @ApiOperation("确认取消订单")
    @RequestMapping(value = "/refuseCannelOrder", method = RequestMethod.POST)
    @ResponseBody
    public Object refuseCannelOrder(@RequestBody DmsOrder entity) {
        DmsOrder order = dmsOrderService.getById(entity.getId());
        order.setOrderStatus(OrderStatus.HAS_PAYMONEY.getValue());
        dmsOrderService.updateById(order);
        return new CommonResult().success(order);
    }

    /**
     * 生成驾校订单
     *
     * @param orderParam
     * @return
     */
    @ApiOperation("根据套餐生成驾校订单")
    @RequestMapping(value = "/generateDriverOrder")
    @ResponseBody
    public Object generateDriverOrder(DriverOrderParam orderParam) {
        UmsMember currentMember = UserUtils.getCurrentMember();
        DmsOrder order = createDriverOrder(orderParam, currentMember);
        int duration = 0;
        if (null != order.getMealId()) {
            QsgMeal meal = mealService.getById(order.getMealId());
            duration = meal.getDuration();
        } else {
            duration = orderParam.getDuration();
        }
        order.setDuration(duration);
        dmsOrderService.save(order);
        return new CommonResult().success(order);
    }

    @ApiOperation("提前开启订单")
    @RequestMapping(value = "/tiqian")
    @ResponseBody
    public Object tiqian(Long orderId) {
        DmsOrder currentOrder = dmsOrderService.getById(orderId);
        QsgDevice device = deviceService.getById(currentOrder.getDeviceId());
        QsgMeal meal = mealService.getById(currentOrder.getMealId());
        int duration = meal.getDuration();
        Date now = new Date();
        String newStartTime = DateUtil.dateToStr(now, "yyyy/MM/dd HH:mm:ss");
        DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        String newEndTime = df.format(new Date(now.getTime() + duration * 60 * 60 * 1000));
        QueryWrapper qw = new QueryWrapper();
        qw.ge("start_time", DateUtil.dateToString(new Date(), "yyyy/MM/dd HH:mm:ss"));
        qw.eq("store_id", currentOrder.getStoreId());
        qw.eq("device_id", currentOrder.getDeviceId());
        List<Integer> statues = new ArrayList<>();
        statues.add(OrderStatus.HAS_PAYMONEY.getValue());
        statues.add(OrderStatus.WAIT_CANNEL.getValue());
        qw.in("order_status", statues);
        List<DmsOrder> orders = dmsOrderService.list(qw);
        if (null != orders && orders.size() > 0) {
            for (DmsOrder order : orders) {
                Boolean res = DateUtil.isIntersect(newStartTime, newEndTime, order.getStartTime(), order.getEndTime());
                if (res && order.getId().intValue() != currentOrder.getId().intValue()) {
                    //存在订单时间重复，返回1
                    return new CommonResult().success(1);
                }
            }
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.ge("end_time", DateUtil.dateToString(new Date(), "yyyy/MM/dd HH:mm:ss"));
        queryWrapper.eq("store_id", currentOrder.getStoreId());
        queryWrapper.eq("device_id", currentOrder.getDeviceId());
        queryWrapper.eq("order_status", OrderStatus.HAS_PAYMONEY.getValue());
        List<DmsOrder> orders1 = dmsOrderService.list(queryWrapper);
        if (null != orders1 && orders1.size() > 0) {
            for (DmsOrder order : orders1) {
                Boolean res = DateUtil.isIntersect(newStartTime, newEndTime, order.getStartTime(), order.getEndTime());
                if (res && order.getId().intValue() != currentOrder.getId().intValue()) {
                    //存在订单时间重复，返回1
                    return new CommonResult().success(1);
                }
            }
        }
        //条件达成提前开启之后   删除掉上一笔订单的任务 生成新的订单 并开门
        currentOrder.setStartTime(newStartTime.substring(0, newStartTime.lastIndexOf(":")));
        currentOrder.setEndTime(newEndTime.substring(0, newEndTime.lastIndexOf(":")));
        dmsOrderService.updateById(currentOrder);
//        QueryWrapper taskQw = new QueryWrapper();
//        taskQw.eq("order_sn",currentOrder.getOrderSn());
//        taskService.remove(taskQw);//删除掉之前的任务
//        //生成新的任务,包括开门
//        QsgDeviceTask task = new QsgDeviceTask();
//        task.setOrderSn(currentOrder.getOrderSn());
//        task.setCreateDatetime(new Date());
//        task.setDeviceCode(device.getDeviceCode());
//        task.setDeviceId(device.getId());
//        String endTime = currentOrder.getEndTime();
//        Date date = new Date(endTime);
//        task.setEndTime(date);
//        task.setTaskType(TaskType.END_REPORT.getValue());
//        taskService.save(task);//结束任务
//        Calendar calendar = Calendar.getInstance();
//        calendar.setTime(date);
//        calendar.add(Calendar.MINUTE,-5);
//        task.setEndTime(calendar.getTime());
//        task.setTaskType(TaskType.FIVE_REPORT.getValue());
//        taskService.save(task);//结束前5分钟
//        calendar.add(Calendar.MINUTE,-25);
//        task.setEndTime(calendar.getTime());
//        task.setTaskType(TaskType.THIRD_REPORT.getValue());
//        taskService.save(task);//结束前三十分钟
        return new CommonResult().success(0);
    }

    @ApiOperation("根据套餐生成驾校订单")
    @RequestMapping(value = "/generateRechargeOrder")
    @ResponseBody
    public Object generateRechargeOrder(QsgRechargeOrder order) {
        UmsMember currentMember = UserUtils.getCurrentMember();
        order.setCreateDatetime(new Date());
        order.setOrderStatus(OrderStatus.INIT.getValue());
        order.setMemberId(currentMember.getId());
        order.setOrderSn(generateRechargeOrderSn(order));
        if (StringUtils.isNotBlank(currentMember.getPhone())) {
            order.setPhone(currentMember.getPhone());
        }
        rechargeOrderService.save(order);
        return new CommonResult().success(order);
    }

    @ApiOperation("删除订单")
    @RequestMapping(value = "/deleteOrder")
    @ResponseBody
    public Object deleteOrder(Long orderId) {
        try {
            dmsOrderService.removeById(orderId);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult().failed();
        }
        return new CommonResult().success();
    }

    /**
     * 第一步
     *
     * @param orderParam
     * @return
     */
    @ApiOperation("查询是否需要保护上一订单")
    @RequestMapping(value = "/checkProtect")
    @ResponseBody
    public Object checkProtect(DriverOrderParam orderParam) {
        QsgStore store = qsgStoreService.getById(orderParam.getStoreId());
        String startTime = orderParam.getStartTime();
        QueryWrapper qw = new QueryWrapper();
        qw.eq("store_id", orderParam.getStoreId());
        qw.eq("order_status", OrderStatus.HAS_PAYMONEY.getValue());
        qw.eq("device_id", orderParam.getDeviceId());
        qw.le("start_time", startTime);//查询出订单表内在此订单开始时间前的订单
        List<DmsOrder> orders = dmsOrderService.list(qw);
        DmsOrder currentOrder = null;
        Date now = new Date();
        if (null != orders && orders.size() > 0) {
            for (DmsOrder order : orders) {
                Date lastOrderEndTime = new Date(order.getEndTime());
                Date lastOrderStartTime = new Date(order.getStartTime());
                if (now.getTime() <= lastOrderEndTime.getTime() && now.getTime() >= lastOrderStartTime.getTime()) {
                    //正在打的
                    currentOrder = order;
                }
            }
            if (null == currentOrder) {
                return new CommonResult().success(0);
            } else {
                String endTime = currentOrder.getEndTime();//上个订单结束时间
                int timeDiff = DateUtil.timeDiff(orderParam.getStartTime(), endTime);
                if (timeDiff < 0) {
                    //上个订单结束在此次订单开始之后,故时间冲突
                    return new CommonResult().success(1);
                } else {
                    //剩余时间
                    int u = DateUtil.timeDiff(currentOrder.getEndTime(), DateUtil.dateToString(now, "yyyy/MM/dd HH:mm:ss"));
                    //此订单开始时间与上笔结束时间相距1小时
                    if (DateUtil.timeDiff(orderParam.getStartTime(), currentOrder.getEndTime()) >= store.getDasaoTime()) {
                        return new CommonResult().success(0);
                    } else {
                        //此订单开始时间与上笔结束时间未相距1小时
                        Long memberId = UserUtils.getCurrentMember().getId();
                        if (memberId.intValue() == currentOrder.getMemberId().intValue()) {
                            return new CommonResult().success(0);
                        }
                        return new CommonResult().success(1);
                    }
                }
            }
        } else {
            return new CommonResult().success(0);
        }
    }


    /**
     * 查询订单时间是否重复 第二步
     *
     * @param orderParam
     * @return
     */
    @ApiOperation("查询订单时间是否重复")
    @RequestMapping(value = "/checkIsIntersect")
    @ResponseBody
    public Object checkIsIntersect(DriverOrderParam orderParam) {
        QueryWrapper qw = new QueryWrapper();
        qw.ge("start_time", DateUtil.dateToString(new Date(), "yyyy/MM/dd HH:mm:ss"));
        qw.eq("store_id", orderParam.getStoreId());
        qw.eq("device_id", orderParam.getDeviceId());
        List<Integer> statues = new ArrayList<>();
        statues.add(OrderStatus.HAS_PAYMONEY.getValue());
        statues.add(OrderStatus.WAIT_CANNEL.getValue());
        statues.add(OrderStatus.PayNotNotice.getValue());
        statues.add(OrderStatus.INIT.getValue());
        qw.in("order_status", statues);
        List<DmsOrder> orders = dmsOrderService.list(qw);
        if (null != orders && orders.size() > 0) {
            for (DmsOrder order : orders) {
                Boolean res = DateUtil.isIntersect(orderParam.getStartTime(), orderParam.getEndTime(), order.getStartTime(), order.getEndTime());
                if (res) {
                    //存在订单时间重复，返回1
                    return new CommonResult().success(1);
                }
            }
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.ge("end_time", DateUtil.dateToString(new Date(), "yyyy/MM/dd HH:mm:ss"));
        queryWrapper.eq("store_id", orderParam.getStoreId());
        queryWrapper.eq("device_id", orderParam.getDeviceId());
        queryWrapper.in("order_status", statues);
        List<DmsOrder> orders1 = dmsOrderService.list(queryWrapper);
        if (null != orders1 && orders1.size() > 0) {
            for (DmsOrder order : orders1) {
                Boolean res = DateUtil.isIntersect(orderParam.getStartTime(), orderParam.getEndTime(), order.getStartTime(), order.getEndTime());
                if (res) {
                    //存在订单时间重复，返回1
                        return new CommonResult().success(1);
                }
            }
        }
        return new CommonResult().success(0);
    }

    @ApiOperation("短链转长链")
    @RequestMapping(value = "/convert", method = RequestMethod.GET)
    @ResponseBody
    public Object convert(String url) {
        try {
            HttpURLConnection conn = (HttpURLConnection) new java.net.URL(url)
                    .openConnection();
            conn.setInstanceFollowRedirects(false);
            conn.setConnectTimeout(5000);
            url = conn.getHeaderField("Location");
            String encrypted_data = UrlUtils.getParam(url, "object_id");
            return new CommonResult().success(encrypted_data);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult().failed();
        }
    }


    /**
     * 兑换美团券
     *
     * @param meituanStoreId 美团店铺ID
     * @param meituanNum     美团券号
     * @return
     */
    @ApiOperation("美团券兑换")
    @RequestMapping(value = "/duiHuan")
    @ResponseBody
    public Object duiHuan(@RequestParam String meituanStoreId, @RequestParam String meituanNum) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("open_shop_uuid", meituanStoreId);
        QsgStore store = qsgStoreService.getOne(qw);
        String meituanSession = store.getMeituanSession();
        Map<String, String> params = new HashMap<>();
        params.put("app_key", store.getMeituanAppid());
        params.put("timestamp", new TimestampValueBuilder().build());
        params.put("session", meituanSession);
        params.put("format", "json");
        params.put("v", "1");
        params.put("sign_method", "MD5");
        params.put("receipt_code", meituanNum);
        params.put("open_shop_uuid", meituanStoreId);
        String returnContent = new TuangouAPI().receiptPrepare(store.getMeituanAppsecret(), params);
        log.info("美团预核销返回:{}", returnContent);
        JSONObject result = JSON.parseObject(returnContent);
        if (result.getIntValue("code") == 200) {
            JSONObject tuangouInfo = result.getJSONObject("data");
            int count = tuangouInfo.getIntValue("count");
            int dealId = tuangouInfo.getIntValue("deal_id");
            String title = tuangouInfo.getString("deal_title");
            BigDecimal price = tuangouInfo.getBigDecimal("deal_price");
            Map<String, String> conditions = new HashMap<>();
            conditions.put("app_key", store.getMeituanAppid());
            conditions.put("timestamp", new TimestampValueBuilder().build());
            conditions.put("session", meituanSession);
            conditions.put("format", "json");
            conditions.put("v", "1");
            conditions.put("sign_method", "MD5");
            conditions.put("receipt_code", meituanNum);
            conditions.put("open_shop_uuid", meituanStoreId);
            conditions.put("requestid", new RequestIdBuilder().build());
            conditions.put("count", String.valueOf(count));
            conditions.put("app_shop_account", String.valueOf(store.getId()));
            conditions.put("app_shop_accountname", String.valueOf(store.getId()));
            String hexiaoContent = new TuangouAPI().receiptConsume(store.getMeituanAppsecret(), conditions);
            JSONObject hexiaoResult = JSON.parseObject(hexiaoContent);
            if (hexiaoResult.getIntValue("code") == 200) {
                UmsMember currentMember = UserUtils.getCurrentMember();
                QueryWrapper jfQw = new QueryWrapper();
                jfQw.eq("store_id", store.getId());
                jfQw.eq("member_id", currentMember.getId());
                QsgIntegral integral = integralService.getOne(jfQw);
                QueryWrapper mealCondi = new QueryWrapper();
                mealCondi.eq("store_id", store.getId());
                mealCondi.eq("meituan_dealid", dealId);
                QsgMeal meal = mealService.getOne(mealCondi);
                if (null != meal) {
                    Integer mealIntegral = meal.getIntegral();
//                    if (null != integral) {
//                        int jifen = integral.getIntegral();
//                        integral.setIntegral(mealIntegral + jifen);
//                        integralService.updateById(integral);
//                    } else {
//                        integral = new QsgIntegral();
//                        integral.setCreateDatetime(new Date());
//                        integral.setMemberId(currentMember.getId().intValue());
//                        integral.setStoreId(store.getId());
//                        integral.setIntegral(mealIntegral);
//                        integralService.save(integral);
//                    }
                    BigDecimal priceNum = BigDecimal.ZERO;
                    if (null!=price){
                        priceNum = price;
                    }
                    Certificate certificate = new Certificate();
                    certificate.setStoreId(store.getId());
                    certificate.setCertificateName(title);
                    certificate.setIntegral(meal.getIntegral());
                    certificate.setMemberId(currentMember.getId().intValue());
                    certificate.setMemberPhone(currentMember.getPhone());
                    certificate.setSourceCode(meituanNum);
                    certificate.setSourceType(1);
                    certificate.setCreateDatetime(new Date());
                    certificateService.save(certificate);
                    this.addHexiaoRecord(meituanNum, currentMember.getId(), currentMember.getNickname(), currentMember.getPhone(), store.getId(), 1, mealIntegral,title,priceNum);
                    UmsMember member = UserUtils.getCurrentMember();
                    if (null!=member){
                        memberUtil.operate(member,store.getId().longValue());
                    }
                    return new CommonResult().success("兑换美团券成功.", 1);
                } else {
                    return new CommonResult().success("套餐配置错误", 2);
                }
            } else {
                return new CommonResult().failed("兑换美团券失败.");
            }
        } else {
            return new CommonResult().failed("兑换美团券失败.");
        }
    }


    /**
     * 兑换抖音券
     *
     * @param douyinPoiid 抖音店铺ID
     * @param douyinNum   抖音券号
     * @return
     */
    @ApiOperation("抖音券兑换")
    @RequestMapping(value = "/douyinDuiHuan")
    @ResponseBody
    public Object douyinDuiHuan(@RequestParam String douyinPoiid, @RequestParam String douyinNum) {
        String price = "";
        String title = "";
        QueryWrapper qw = new QueryWrapper();
        qw.eq("douyin_poi_id", douyinPoiid);
        QsgStore store = qsgStoreService.getOne(qw);
        String douyinToken = store.getDouyinToken();
        TuangouHexiaoPrepareResponse200 returnContent = new TuangouHexiaoPrepareApi().dataTuangouPrepareGet(douyinNum, douyinToken);
        log.info("抖音预核销返回:{}", returnContent);
        TuangouHexiaoPrepareResponse200Data response200Data = returnContent.getData();
        Integer errorCode = response200Data.getErrorCode();
        if (errorCode == 0) {
            String verifyToken = response200Data.getVerifyToken();
            String encryptedCode = "";
            String thirdSkuId = "";
            if (response200Data.getCertificates().size() > 0) {
                encryptedCode = response200Data.getCertificates().get(0).getEncryptedCode();
                thirdSkuId = response200Data.getCertificates().get(0).getSku().getThirdSkuId();
                title = response200Data.getCertificates().get(0).getSku().getTitle();
                price = response200Data.getCertificates().get(0).getAmount().getOriginalAmount();
            }
            TuangouHexiaoResponse200 hexiaoContent = new TuangouHexiaoApi().hexiaoPost(verifyToken, douyinPoiid, encryptedCode, douyinToken);
            TuangouHexiaoResponse200Data hexiaoResponse200Data = hexiaoContent.getData();
            if (hexiaoResponse200Data.getErrorCode() == 0) {
                UmsMember currentMember = UserUtils.getCurrentMember();
                QsgMeal meal = mealService.getById(thirdSkuId);
                if (null != meal) {
//                    Integer mealIntegral = meal.getIntegral();
//                    if (null != integral) {
//                        int jifen = integral.getIntegral();
//                        integral.setIntegral(mealIntegral + jifen);
//                        integralService.updateById(integral);
//                    } else {
//                        integral = new QsgIntegral();
//                        integral.setCreateDatetime(new Date());
//                        integral.setMemberId(currentMember.getId().intValue());
//                        integral.setStoreId(store.getId());
//                        integral.setIntegral(mealIntegral);
//                        integralService.save(integral);
//                    }
                    Certificate certificate = new Certificate();
                    certificate.setStoreId(store.getId());
                    certificate.setCertificateName(title);
                    certificate.setIntegral(meal.getIntegral());
                    certificate.setMemberId(currentMember.getId().intValue());
                    certificate.setMemberPhone(currentMember.getPhone());
                    certificate.setSourceCode(douyinNum);
                    certificate.setSourceType(0);
                    certificate.setCreateDatetime(new Date());
                    certificateService.save(certificate);
                    BigDecimal priceNum = BigDecimal.ZERO;
                    if (StringUtils.isNotBlank(price)){
                        priceNum = new BigDecimal(price).divide(new BigDecimal("100"));
                    }
                    this.addHexiaoRecord(douyinNum,currentMember.getId(),currentMember.getNickname(),currentMember.getPhone(),store.getId(),0,meal.getIntegral(),title,priceNum);
                    UmsMember member = UserUtils.getCurrentMember();
                    if (null!=member){
                        memberUtil.operate(member,store.getId().longValue());
                    }
                    return new CommonResult().success("兑换抖音券成功.", 1);
                } else {
                    return new CommonResult().success("套餐配置错误", 2);
                }
            } else {
                return new CommonResult().failed("兑换抖音券失败.");
            }
        } else {
            return new CommonResult().failed("兑换抖音券失败.");
        }
    }

    private void addIntegralDetail(Integer memberId, Integer storeId, int integral) {
        QsgIntegralDetail detail = new QsgIntegralDetail();
        detail.setIntegral("-" + integral);
        detail.setCreateDatetime(new Date());
        detail.setMemberId(memberId.longValue());
        detail.setStoreId(storeId.longValue());
        detail.setTypeName("抖音核销");
        detailService.save(detail);
    }

    private void addHexiaoRecord(String code, Long memberId, String memberName, String memberPhone, Integer storeId, int hexiaoType, int integral,String title,BigDecimal price) {
        QsgHexiao hexiao = new QsgHexiao();
        hexiao.setCode(code);
        hexiao.setCreateDatetime(new Date());
        hexiao.setHexiaoType(hexiaoType);
        hexiao.setIntegral(integral);
        hexiao.setTitle(title);
        hexiao.setPrice(price);
        hexiao.setMemberId(memberId);
        hexiao.setMemberName(memberName);
        if (StringUtils.isNotBlank(memberPhone)) {
            hexiao.setMemberPhone(memberPhone);
        }
        hexiao.setStoreId(storeId);
        hexiaoService.save(hexiao);
    }

    private DmsOrder createDriverOrder(DriverOrderParam orderParam, UmsMember currentMember) {
        DmsOrder order = new DmsOrder();
        order.setDeviceId(orderParam.getDeviceId());
        order.setMemberId(currentMember.getId());
        order.setMemberName(currentMember.getPhone());
        order.setCreateDatetime(new Date());
        order.setMealId(orderParam.getMealId());
        order.setMealName(orderParam.getMealName());
        order.setOrderStatus(OrderStatus.INIT.getValue());
        order.setOrderSn(generateDriverOrderSn(order));
        order.setPrice(orderParam.getPrice());
        order.setDeviceId(orderParam.getDeviceId());
        order.setStartTime(orderParam.getStartTime());
        order.setEndTime(orderParam.getEndTime());
        order.setStoreId(orderParam.getStoreId());
        order.setCertId(orderParam.getCertId());
        return order;
    }

    private String generateDriverOrderSn(DmsOrder order) {
        StringBuilder sb = new StringBuilder();
        sb.append(System.currentTimeMillis());
        sb.append(order.getMemberId());
        return sb.toString();
    }

    private String generateRechargeOrderSn(QsgRechargeOrder order) {
        StringBuilder sb = new StringBuilder();
        sb.append("CZ");
        sb.append(System.currentTimeMillis());
        sb.append(order.getMemberId());
        return sb.toString();
    }
}
